<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="资金名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入资金名称" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" clearable placeholder="请选择项目">
          <el-option v-for="dict in projectList" :key="dict.id" :label="dict.name" :value="parseInt(dict.id)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-sort" plain size="mini" type="info" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="fundList" :default-expand-all="isExpandAll"
      :row-key="row => row.projectId + row.taskId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="资金名称" prop="name" />
      <el-table-column align="center" label="所属">

        <template slot-scope="scope">
          <div v-if="scope.row.name == scope.row.projectName">
            {{ scope.row.projectName }}
          </div>
          <div v-else>
            {{ scope.row.taskName }}
          </div>
        </template>

      </el-table-column>
      <el-table-column align="center" label="总资金" prop="totalFunding" />
      <el-table-column align="center" label="已使用总资金" prop="usedFunding" />
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:fund:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">分配
          </el-button>
          <el-button v-has-permi="['system:fund:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改资金对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资金名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入资金名称" />
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-input v-model="form.projectName" :disabled="true" :normalizer="normalizer" :options="fundOptions"
            placeholder="请选择项目" />

        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-input v-model="form.taskName" :disabled="true" :normalizer="normalizer" :options="fundOptions"
            placeholder="当前条目为项目" />
        </el-form-item>

        <el-form-item label="省份资金" prop="provinceFunding">
          <el-input-number v-model="form.provinceFunding" :disabled="currentUser" placeholder="省份资金"
            :min="form.usedProvinceFunding" :max="this.maxProvinceFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>
        <el-form-item label="省份开销" prop="usedProvinceFunding" v-if="form.taskId != 0 && form.provinceFunding">
          <el-input-number v-model="form.usedProvinceFunding" placeholder="省份开销" :min="0" :max="form.provinceFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>

        <el-form-item label="市级资金" prop="cityFunding">
          <el-input-number v-model="form.cityFunding" :disabled="currentUser" placeholder="市级资金"
            :min="form.usedCityFunding" :max="this.maxCityFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>
        <el-form-item label="市级开销" prop="usedCityFunding" v-if="form.taskId != 0 && form.cityFunding">
          <el-input-number v-model="form.usedCityFunding" placeholder="市级开销" :min="0" :max="form.cityFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>

        <el-form-item label="公司资金" prop="companyFunding">
          <el-input-number v-model="form.companyFunding" :disabled="currentUser" placeholder="公司资金"
            :min="form.usedCompanyFunding" :max="this.maxCompanyFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>
        <el-form-item label="公司开销" prop="usedCompanyFunding" v-if="form.taskId != 0 && form.companyFunding">
          <el-input-number v-model="form.usedCompanyFunding" placeholder="公司开销" :min="0" :max="form.companyFunding" />
          <span style="margin-left: 20px;">￥</span>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addFund, delFund, getFund, getFundInfo, listFund, updateFund } from "@/api/system/fund";
import { listProject } from "@/api/system/project"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getProjectUsedFunding } from "../../../api/system/fund";

export default {
  name: "Fund",
  dicts: ['sys_user_sex', 'moe_fund_status'],
  components: {
    Treeselect
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 资金表格数据
      fundList: [],
      // 项目表格数据
      projectList: [],
      // 资金树选项
      fundOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: null,
        projectId: null,
        status: null,
      },
      // 最大省份资金
      maxProvinceFunding: Number.MAX_SAFE_INTEGER,
      // 最大城市资金
      maxCityFunding: Number.MAX_SAFE_INTEGER,
      // 最大公司资金
      maxCompanyFunding: Number.MAX_SAFE_INTEGER,
      // 表单参数
      form: {},
      // 当前登录的用户角色id
      currentUser: null,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "资金名称不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "项目不能为空", trigger: "change" }
        ],
        provinceFunding: [
          { required: true, message: "省份资金不能为空", trigger: "blur" }
        ],
        cityFunding: [
          { required: true, message: "市级资金不能为空", trigger: "blur" }
        ],
        companyFunding: [
          { required: true, message: "公司资金不能为空", trigger: "blur" }
        ],
        usedProvinceFunding: [
          { required: true, message: "已使用省份资金不能为空", trigger: "blur" }
        ],
        usedCityFunding: [
          { required: true, message: "已使用市级资金不能为空", trigger: "blur" }
        ],
        usedCompanyFunding: [
          { required: true, message: "已使用公司资金不能为空", trigger: "blur" }
        ],
        totalFunding: [
          { required: true, message: "总资金不能为空", trigger: "blur" }
        ],
        usedFunding: [
          { required: true, message: "已使用总资金不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created () {
    this.getList();
    this.getProject()
  },
  methods: {
    /** 查询资金列表 */
    getList () {
      this.loading = true;
      listFund(this.queryParams).then(response => {
        this.fundList = this.Tree(response.data, "projectId", "taskId");
        this.loading = false;
      });
    },
    getProject () {
      listProject().then(
        response => {
          this.projectList = response.rows
        }
      )
    },

    // 树结构
    Tree (data, id, parentId, children) {
      const categorizedData = {};
      data.forEach(item => {
        const projectId = item.projectId;
        const taskId = item.taskId;
        if (!categorizedData[projectId]) {
          categorizedData[projectId] = { id: projectId, children: [] };
        }
        if (taskId === 0) {
          categorizedData[projectId] = { ...item, children: [] };
        } else {
          if (categorizedData[projectId]) {
            categorizedData[projectId].children.push(item);
          }
        }
      });
      return Object.values(categorizedData)
    },
    /** 转换资金数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.projectId,
        label: node.name,
        children: node.children
      };
    },
    /** 查询资金下拉树结构 */
    getTreeselect () {
      listFund().then(response => {
        this.fundOptions = [];
        const data = { projectId: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "projectId", "taskId");
        this.fundOptions.push(data);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        name: null,
        projectId: null,
        taskId: null,
        provinceFunding: null,
        cityFunding: null,
        companyFunding: null,
        usedProvinceFunding: null,
        usedCityFunding: null,
        usedCompanyFunding: null,
        totalFunding: null,
        usedFunding: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.maxProvinceFunding = Number.MAX_SAFE_INTEGER
      this.maxCityFunding = Number.MAX_SAFE_INTEGER
      this.maxCompanyFunding = Number.MAX_SAFE_INTEGER
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.projectId) {
        this.form.taskId = row.projectId;
      } else {
        this.form.taskId = 0;
      }
      this.open = true;
      this.title = "添加资金";
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 资金修改权限
    fundPower () {
      // 获取当前登录的角色id
      let roleid = localStorage.getItem('currentRole')
      if (roleid == 'project-admin') {
        if (this.form.taskName == null) {
          return false
        } else {
          return true
        }
      }
      if (roleid == 'project-manager') {
        if (this.form.taskName == null) {
          return true
        } else {
          return false
        }
      }
    },
    /** 修改按钮操作 */
    async handleUpdate (row) {
      this.reset();
      this.getTreeselect();
      if (row.taskId != 0) {
        getFundInfo({
          projectId: row.projectId,
          taskId: 0
        }).then((response) => {
          getProjectUsedFunding(row.projectId).then((projectUsedResponse) => {
            this.maxProvinceFunding = response.data.provinceFunding - projectUsedResponse.data.provinceFunding + row.provinceFunding;
            this.maxCityFunding = response.data.cityFunding - projectUsedResponse.data.cityFunding + row.cityFunding;
            this.maxCompanyFunding = response.data.companyFunding - projectUsedResponse.data.companyFunding + row.companyFunding;
          })
        })
      }
      getFund(row.id).then(response => {
        this.form = response.data;
        this.currentUser = this.fundPower()
        this.open = true;
        this.title = "修改资金";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFund(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFund(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除资金编号为"' + row.id + '"的数据项？').then(function () {
        return delFund(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
